package com.shujia.MR;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;

import java.io.IOException;

public class MapReduce03 {
    // Mapper
    public static class MyMapper extends Mapper<LongWritable, Text, Text, DoubleWritable> {
        @Override
        protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, DoubleWritable>.Context context) throws IOException, InterruptedException {
            String[] splits = value.toString().split(",");
            String xmlb = splits[2];
            String id = splits[3];
            double dkje_rmb = Double.parseDouble(splits[6]);

            context.write(new Text(xmlb + "," + id), new DoubleWritable(dkje_rmb));
        }
    }

    // Reducer
    public static class MyReducer extends Reducer<Text, DoubleWritable, Text, DoubleWritable> {
        @Override
        protected void reduce(Text key, Iterable<DoubleWritable> values, Reducer<Text, DoubleWritable, Text, DoubleWritable>.Context context) throws IOException, InterruptedException {
            double sum_dkje_rmb = 0;
            for (DoubleWritable value : values) {
                sum_dkje_rmb += value.get();
            }
            context.write(key,new DoubleWritable(sum_dkje_rmb));
        }
    }

    // Driver
    public static void main(String[] args) throws IOException, InterruptedException, ClassNotFoundException {
        Configuration conf = new Configuration();

        Job job = Job.getInstance(conf);
        job.setJobName("MapReduce03");
        job.setJarByClass(MapReduce03.class);

        // 设置Map端
        job.setMapperClass(MyMapper.class);
        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(DoubleWritable.class);
        // 设置Reduce端
        job.setReducerClass(MyReducer.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(DoubleWritable.class);

        // 设置输入输出路径
        FileInputFormat.addInputPath(job, new Path("/data/MR/output1/"));

        // 判断输出路径是否存在
        FileSystem fs = FileSystem.get(conf);
        Path path = new Path("/data/MR/output3-1");
        if (fs.exists(path)) {
            fs.delete(path, true);
        }

        FileOutputFormat.setOutputPath(job, path);

        job.waitForCompletion(true);

        // hadoop jar Competition2021-1.0.jar com.shujia.MR.MapReduce03
    }
}
